package phase01.module4.code.question1;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Database<T> {
    private static Database instance;
    private List<T> db;
    private final String DATA_FILE;

    public static Database getInstance() {
        if (null == instance) {
            instance = new Database();
        }
        return instance;
    }

    private Database() {
        DATA_FILE = "data.bin";
        db = new ArrayList<>();
    }

    public void insert(T value) throws Exception {
        try {
            db.add(value);
        } catch (Exception e) {
            throw new Exception("Insert failed." + e.getMessage());
        }
    }

    public void delete(T data) {
        db.remove(data);
    }

    public void update(T data) {
         int idx = db.indexOf(data);
         if(idx >= 0) {
             db.remove(idx);
             db.add(idx, data);
         }
    }

    public void commit() {
        // save data list to file
        try (FileOutputStream fileOutputStream = new FileOutputStream(DATA_FILE); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
            objectOutputStream.writeObject(db);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @SuppressWarnings("unchecked")
    public void load() {
        try(FileInputStream fileInputStream = new FileInputStream(DATA_FILE); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
            db = (List<T>) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("数据文件还未创建");
        }
    }

    public T find(T data) {
        int idx = db.indexOf(data);
        if(idx >= 0) {
            return db.get(idx);
        } else {
            return null;
        }
    }

    public void show() {
        for(T val: db) {
            System.out.println(val);
        }
    }

}
